import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Alert,
  Dimensions,
} from 'react-native';

import styles from './sellRecordStyle';
import CustomListView from '../global/CustomListView';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';
import api from '../../services/api';
import _ from 'lodash';
import ToastTip from '../global/ToastTip';
import * as config from '../../constants/apiConfig';
import Communications from 'react-native-communications';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class SellRecordList extends Component {
     constructor(props) {
        super(props);

        this.state = {
            noData: false,
            listData:null,
        };

        // this._page = 0;
        this.totalpage = 0;
        this.pagesize = 20;
        this.list = [];
        this.currentPage = 1;


        // this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
    }

    componentDidMount() {
        this.onLoad();
    }

    onLoad(){
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._withdrawByList._pullToRefreshListView.beginRefresh(true);
    }

    componentWillUnmount () {

    }

    _onSearchResultListItemPress(rowData){
        // this.props.parent.setState({addressFirst: `${rowData.first_address}${rowData.second_address}`});
    }

    async _getWithdrawList(){
        this._withdrawByList._pullToRefreshListView.clearListRowRefsCache();
        let {type} = this.props;
        let status = type == "complete"?1:2;
        let totalMoneyData = await api.post('/privilege/shops/keeperVoucherTotal',{
            status:status
        })
        if (totalMoneyData.cd != 0) {
            this.refs.toast.show(totalMoneyData.msg);
            this.setState({
                totalMoney:0,
            })
            return;
        }else{
            
            let list = await api.post('/privilege/shops/keeperVoucherList', {
                   page:1,
                   status:status,
                   pagesize:this.pagesize
                });
        
            console.log('testddddddddddddddddd',list);

           this.list = {};

           if(Platform.OS == 'ios') {
               this._endWithdrawList(list.data,totalMoneyData.data);
           } else {
               setTimeout(() => {
                   this._endWithdrawList(list.data,totalMoneyData.data);
               }, 300);
           }
        }
        
    }

    // async _getWithdrawList(){

    //     let list;
    //     let totalMoneyData;
    //     let {type} = this.props;
    //     let status = type == "complete"?1:2;

    //     //need to clear ListRowRefsCache manually
    //     this._withdrawByList._pullToRefreshListView.clearListRowRefsCache();

        
    //     list = await api.post('/privilege/shops/keeperVoucherList', {
    //                page:1,
    //                status:status,
    //                pagesize:this.pagesize
    //             });
        
    //     console.log('testddddddddddddddddd',list);

    //    this.list = {};

    //    if(Platform.OS == 'ios') {
    //        this._endWithdrawList(list.data);
    //    } else {
    //        setTimeout(() => {
    //            this._endWithdrawList(list.data);
    //        }, 300);
    //    }
    // }

    _endWithdrawList(list,totalMoney){

        // console.log("###", list);
        if(list==null || list.count == 0 || list.res == null || list.res.length==0){
            this.setState({noData: true});
            return;
        }


        this.totalpage = list.total_page;
        list = list.res;

        let {type} = this.props;
        

        for (var i = 0; i < list.length; i++) {
            let dateArr;
            if (type == "complete") {
                dateArr = list[i].usedTime?list[i].usedTime.split("-"):["",""];
            }else{
                dateArr = list[i].refundTime?list[i].refundTime.split("-"):["",""];
            }
            
            if(this.list[dateArr[0]+'年'+dateArr[1]+'月']){
                this.list[dateArr[0]+'年'+dateArr[1]+'月'].push(list[i]);
            }else{
                this.list[dateArr[0]+'年'+dateArr[1]+'月'] = [list[i]];
            }
        }

        this.setState({
            listData:{...this.list},
            totalMoney:totalMoney,
            
        })
        let list_copy = {...this.list};
        // this._updateListView();cloneWithRowsAndSections
        this.currentPage=1;
        this._withdrawByList && this._withdrawByList.setState({
            dataSource: this._withdrawByList._dataSource.cloneWithRowsAndSections(list_copy)
        });
        this._activityIndicator && this._activityIndicator.setState({ visible: false,});
        this._withdrawByList && this._withdrawByList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage() {
        let page, list;
        let {type} = this.props;
        let status = type == "complete"?1:2;
        if (this.currentPage !== this.totalpage) {
            page = this.currentPage + 1;
            this.currentPage=page;

            list = await api.post('/privilege/shops/keeperVoucherList', {
                       page:page,
                       status:status,
                       pagesize:this.pagesize

                    });
            console.log('test0000000000000000000-----------',list);
            if(list.data){
                const newData = list.data.res;

                let {type} = this.props;
                for (var i = 0; i < newData.length; i++) {
                    let dateArr;
                    if (type == "complete") {
                        dateArr = newData[i].usedTime.split("-");
                    }else{
                        dateArr = newData[i].refundTime.split("-");
                    }

                    if(this.list[dateArr[0]+'年'+dateArr[1]+'月']){
                        this.list[dateArr[0]+'年'+dateArr[1]+'月'].push(newData[i]);
                    }else{
                        this.list[dateArr[0]+'年'+dateArr[1]+'月'] = [newData[i]];
                    }
                }

                // newData.map((item, index) => this.list.push(item));

                this._withdrawByList.setState({
                    dataSource: this._withdrawByList._dataSource.cloneWithRowsAndSections(this.list),
                });

                this._withdrawByList._pullToRefreshListView.endLoadMore(false);
            }

        }else{
            this._withdrawByList._pullToRefreshListView.endLoadMore(true);
        }

    }

    _onRefresh(){
        this._getWithdrawList();
    }

    _onLoadMore(){
        this._retrieveNextPage();
    }


    _renderFloatSectionHeader(sectionID){
        return null;
        // return (
        //     <View style={{paddingLeft:15,paddingTop:5,paddingBottom:5,backgroundColor:'#fff',borderBottomWidth:StyleSheet.hairlineWidth,borderColor:'#DEDEDE'}}>
        //         <Text style={{color: '#565656'}}>{sectionID}</Text>
        //     </View>
        // )
    }

    _renderSectionHeader(sectionData, sectionID){
        return (
            <View style={{paddingLeft:15,paddingTop:5,paddingBottom:5,backgroundColor:'#fff',borderBottomWidth:StyleSheet.hairlineWidth,borderColor:'#DEDEDE'}}>
                <Text style={{color: '#565656'}}>{sectionID}</Text>
            </View>
        )
    }

    _maskPhone(phone){
        return phone.replace(/(\d{3})\d{6}(\d{2})/, '$1******$2');
    }


    _renderRow(rowData, sectionID, rowID){
        let {type} = this.props;
        return (
            <View style={[styles.searchItem,{marginLeft:0,flexDirection: 'row',alignItems:'center',justifyContent:'space-between'}]}>
                <View style={{paddingLeft: 15,width:'60%',marginTop:15,marginBottom:15}}>
                    <Text style={{fontSize: 15, color: '#555555',}}>{rowData.goodsName}-{rowData.number}</Text>
                    <Text style={{fontSize: 13, color: '#7B7B7B', marginTop: 5, }}>用户：{this._maskPhone(rowData.ownerPhone)}</Text>
                </View>
                <View style={{marginRight: 15,marginTop:15,marginBottom:15}}>
                    <Text style={type == "complete"?styles.moneyComplete:styles.moneyRefund}>¥{rowData.shopsIncome.toFixed(2)}</Text>
                    <Text style={{fontSize: 13, color: '#7B7B7B', marginTop: 5, textAlign:'right'}}>{type == "complete"?rowData.usedTime:rowData.refundTime}</Text>
                </View>
            </View>
        );
    }

    _renderNodata(){
        return (
            <View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Image source={require('../../../img/hk_nodata_icon.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无记录</Text>
            </View>
        );
    }

    render() {
        let {type} = this.props;
        return (
            this.state.noData?this._renderNodata():
            <View style={styles.withdrawContainer}>

            {(this.state.listData == null || (this.state.listData != null && this.state.listData.length == 0))?
                null
                :
                    <View style={type == "complete" ? styles.completeMoneyContainer:styles.refundMoneyContanier}>
                        <Text style={styles.moneyTitle}>
                            {type == "complete" ? `已入账：`:`退款总额：`}
                        </Text>
                        <Text style={type == "complete" ? styles.completeMoney:styles.refundMoney}>
                            {this.state.totalMoney?`¥${this.state.totalMoney.toFixed(2)}`:`--`}
                        </Text>
                    </View>
            }
                
                    
                    <CustomListView
                        style={{flex:1}}
                        ref={ (component) => this._withdrawByList = component }
                        onRefresh={this._onRefresh.bind(this)}
                        onLoadMore={this._onLoadMore.bind(this)}
                        renderRow ={this._renderRow.bind(this)}
                        renderFloatSectionHeader={this._renderFloatSectionHeader.bind(this)}
                        renderSectionHeader={this._renderSectionHeader.bind(this)}
                        

                    />

                <ListViewActivityIndicator
                    ref={ (component) => this._activityIndicator = component }
                    style={{marginRight: 10, position:'absolute', left: (deviceWidth - 20) / 2, top: (deviceHeight - 64 - 70) / 2, }}
                    color={'#a9a9a9'}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
SellRecordList = connectHelper(state => state)(SellRecordList);

module.exports = SellRecordList;
